package com.xuecheng.base.exception;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * Date:2023/7/7
 * Author:丐版小杨哥
 * Description:
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(XueChengPlusException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultException customException(XueChengPlusException e){
        String errMessage = e.getErrMessage();
        return new ResultException(errMessage);
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultException exception(Exception e){
        String message = e.getMessage();
        log.error("系统异常{}", e.getMessage(), e);
        ResultException resultException = new ResultException(CommonError.UNKOWN_ERROR.getErrMessage());
        return resultException;
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultException MethodArgumentNotValidException(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> errorsList = bindingResult.getFieldErrors();
        errorsList.stream().forEach(item->{
            errorsList.add(item);
        });
        String errorMessage = StringUtils.join(errorsList, ",");
        ResultException resultException = new ResultException(errorMessage);
        return resultException;
    }
}